package o2o.delivery.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.util.*;

public class ParameterServletRequestWrapper extends HttpServletRequestWrapper {
 
    private Map<String , String[]> params = new HashMap<String, String[]>();

    public ParameterServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        this.params.putAll(request.getParameterMap());
    }
 
    /**
     * 重载一个构造方法
     * @param request
     * @param extendParams
     */
    public ParameterServletRequestWrapper(HttpServletRequest request , Map<String , String[]> extendParams) throws IOException {
        super(request);
        addAllParameters(extendParams);
    }
 
    @Override
    public String getParameter(String name) {
        String[]values = params.get(name);
        if(values == null || values.length == 0) {
            return null;
        }
        return values[0];
    }
 
    @Override
    public String[] getParameterValues(String name) {
        return params.get(name);
    }

    @Override
    public Enumeration<String> getParameterNames() {
        Set<String> set = params.keySet();
        return Collections.enumeration(set);
    }

    public void addAllParameters(Map<String , String[]>otherParams) {
        for(Map.Entry<String , String[]>entry : otherParams.entrySet()) {
            addParameter(entry.getKey() , entry.getValue());
        }
    }
 
 
    public void addParameter(String name , Object value) {
        //处理name
        name = nameToDealWith(name);
        if(value != null) {
            if(value instanceof String[]) {
                params.put(name , (String[])value);
            }else if(value instanceof String) {
                params.put(name , new String[] {(String)value});
            }else {
                params.put(name , new String[] {String.valueOf(value)});
            }
        }
    }

    private static String nameToDealWith(String name) {
        //如果name是二维数组类型（name[0][name]）
        if (name.matches("\\w*[\\[][0-9]{1,}][\\[]\\w*]")){
            StringBuilder sb = new StringBuilder();
            sb.append(name.substring(0,name.lastIndexOf("[")))
                    .append(".")
                    .append(name.substring(name.lastIndexOf("[")+1,name.lastIndexOf("]")));
            return sb.toString();
        }
        return name;
    }
}
